package main

import (
	"fmt"
	"math/rand"
	"sort"
)

type Student struct {
	Name  string
	Age   int
	Score float64
}

type StudentSlice []Student

func (stu StudentSlice) Len() int {
	return len(stu)
}

// Less 方法就是决定你使用什么标准进行排序
func (stu StudentSlice) Less(i, j int) bool {
	return stu[i].Score > stu[j].Score
}

func (stu StudentSlice) Swap(i, j int) {
	// 交换
	// temp := hs[i]
	// hs[i] = hs[j]
	// hs[j] = temp
	stu[i], stu[j] = stu[j], stu[i]
}

// 结构体切片排序
func main() {
	//要求对结构体切片进行排序
	//1.冒泡排序
	//2.系统方法
	var students StudentSlice
	for i := 0; i < 5; i++ {
		stu := Student{
			Name:  fmt.Sprintf("学生~%d", rand.Intn(100)),
			Age:   rand.Intn(100),
			Score: rand.Float64(),
		}
		students = append(students, stu)
	}

	//排序前的顺序
	for _, v := range students {
		fmt.Println(v)
	}
	//调用sort.Sort方法
	sort.Sort(students)
	fmt.Println("排序后")
	for _, v := range students {
		fmt.Println(v)
	}
}
